package com.vitabuybuy.tv.ui.shopcenter.store

import android.os.Bundle
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.library.common.base.BaseFragment
import com.library.common.base.MessageModel
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.FragmentShopHomeGetCouponsBinding
import com.vitabuybuy.tv.dto.CouponCenterDto
import com.library.common.toast.XToast
import com.vitabuybuy.tv.ui.shopcenter.store.viewmodel.StoreHomeViewModel
import kotlinx.android.synthetic.main.activity_coupons_center.*

class StoreHomeGetCouponsFragment :
    BaseFragment<StoreHomeViewModel, FragmentShopHomeGetCouponsBinding>() {
    override val layoutId: Int
        get() = R.layout.fragment_shop_home_get_coupons
    private var storeId:Int? = -1
    private var pageNumber = 1
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.mViewModel = viewModel
        storeId = (parentFragment as StoreHomeFragment).getStoreId()
    }

    override fun lazyLoadData() {
        viewModel.getCouponList(pageNumber, storeId)
    }

    override fun eventHandling() {
        refresh.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber++
                viewModel.getCouponList(pageNumber, storeId)
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber = 1
                viewModel.getCouponList(pageNumber, storeId)
            }
        })
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            0 -> {
                pageNumber = 1
                viewModel.getCouponList(pageNumber, storeId)
            }
            1 -> {
                refresh.onLoad(msg.arg1)
            }
            2 -> {
                viewModel.saveACoupon((msg.obj as CouponCenterDto).id, msg.arg1)
            }
            3 -> {
                viewModel.couponList[msg.arg1].isReceived = true
                XToast.success(getString(R.string.already_save_coupon))
            }
        }
    }
}
